import 'dart:async';

import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/modules/device/domain/states/pair_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PairnetProcessButton extends StatefulWidget {
  final PairState state;
  final bool isQueued;
  final VoidCallback? onIdleTap;
  final VoidCallback? onFailedTap;
  final VoidCallback? onSuccessTap;

  const PairnetProcessButton({
    super.key,
    required this.state,
    this.isQueued = false,
    this.onIdleTap,
    this.onFailedTap,
    this.onSuccessTap,
  });

  @override
  State<PairnetProcessButton> createState() => _PairnetProcessButtonState();
}

class _PairnetProcessButtonState extends State<PairnetProcessButton>
    with SingleTickerProviderStateMixin {
  // 内部常量：固定3分钟处理时长
  static const _kProcessDuration = Duration(
    seconds: CommonConfig.pairNet_device_timeout,
  );

  late AnimationController _animationController;
  Timer? _processTimer;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: _kProcessDuration,
    )..addListener(() => setState(() {}));

    // 如果初始状态是process，启动计时器
    if (widget.state == PairState.process && !widget.isQueued) {
      _startProcess();
    }
  }

  @override
  void didUpdateWidget(PairnetProcessButton oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 状态变化处理
    if (widget.state != oldWidget.state || widget.isQueued != oldWidget.isQueued) {
      _handleStateChange(widget.state);
    }
  }

  void _handleStateChange(PairState newState) {
    switch (newState) {
      case PairState.process:
        if (!widget.isQueued) {
          _startProcess();
        } else {
          _animationController.reset();
          _processTimer?.cancel();
        }
        break;
      case PairState.failed:
        _animationController.reset();
        _processTimer?.cancel();
        // widget.onFailed?.call();
        break;
      case PairState.success:
        _animationController.reset();
        _processTimer?.cancel();
        // widget.onSuccess?.call();
        break;
      case PairState.idle:
        _animationController.reset();
        _processTimer?.cancel();
        break;
    }
  }

  void _startProcess() {
    _animationController.forward();
    _processTimer = Timer(_kProcessDuration, () {
      if (mounted) {
        // 超时后自动转为failed状态
        // widget.onFailedTap?.call();
        // widget.state = PairState.failed;
      }
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    _processTimer?.cancel();
    super.dispose();
  }

  void _handleTap() {
    switch (widget.state) {
      case PairState.idle:
        widget.onIdleTap?.call();
        break;
      case PairState.process:
        // 处理中状态不可点击
        break;
      case PairState.failed:
        widget.onFailedTap?.call(); // 失败后可重新开始
        break;
      case PairState.success:
        widget.onSuccessTap?.call(); // 成功后可点击
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: _handleTap,
      child: Container(
        width: 56.w,
        height: 32.h,
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          child: _buildStateContent(context),
        ),
      ),
    );
  }

  Widget _buildStateContent(BuildContext context) {
    switch (widget.state) {
      case PairState.idle:
        return _buildIdleState();
      case PairState.process:
        return _buildProcessState(context);
      case PairState.success:
        return _buildSuccessState(context);
      case PairState.failed: // failed状态使用与idle相同的样式
        return _buildFailedState();
    }
  }

  Widget _buildIdleState() {
    return Container(
      key: const ValueKey('idle_state'),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF9470FF), Color(0xFF6652F9)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Center(
        child: Text(
          widget.state == PairState.failed ? '重试' : '添加',
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.r,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Widget _buildProcessState(BuildContext context) {
    if (widget.isQueued) {
      return SizedBox(
        key: const ValueKey('queue_state'),
        width: 56.w,
        height: 32.h,
        child: Center(
          child: SizedBox(
            width: 18.w,
            height: 18.w,
            child: CircularProgressIndicator(
              strokeWidth: 2.w,
              valueColor: AlwaysStoppedAnimation<Color>(
                context.colorScheme.primary,
              ),
            ),
          ),
        ),
      );
    }
    return Stack(
      key: const ValueKey('process_state'),
      alignment: Alignment.center,
      children: [
        // 进度圆环（限制最大0.9）
        SizedBox(
          width: 32.w,
          height: 32.w,
          child: CircularProgressIndicator(
            value: _animationController.value * 0.9,
            strokeWidth: 2.w,
            backgroundColor: Colors.grey[300],
            valueColor: AlwaysStoppedAnimation<Color>(
              context.colorScheme.primary,
            ),
          ),
        ),
        // 中心方块
        Container(width: 8.w, height: 8.w, color: context.colorScheme.primary),
      ],
    );
  }

  Widget _buildSuccessState(BuildContext context) {
    return TextButton(
      key: const ValueKey('success_state'),
      style: TextButton.styleFrom(
        padding: EdgeInsets.zero,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
      onPressed: _handleTap,
      child: Text(
        '重命名',
        style: context.textTheme.bodyLarge!.copyWith(
          color: context.colorScheme.primary,
        ),
      ),
    );
  }

  Widget _buildFailedState() {
    return Container(
      key: const ValueKey('idle_state'),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF9470FF), Color(0xFF6652F9)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Center(
        child: Text(
          '重试',
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.r,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
